package com.ryze.common.dubbo.exception;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.util.Assert;

/**
 * 统一异常类型
 */
@Slf4j
@Getter
public class RyzeException extends RuntimeException {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**
     * 错误码
     */
    private int code;
    private String desc;
    private Object data;

    public void setErrorCode(RyzeErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.desc = errorCode.getDesc();
    }

    public RyzeErrorCode getErrorCode(){
        return new RyzeErrorCode() {
            @Override
            public int getCode() {
                return code;
            }
            @Override
            public String getDesc() {
                return desc;
            }
        };
    }

    public RyzeException(){
    }

    public RyzeException(int code, String desc){
        super(desc);
        this.code = code;
        this.desc = desc;
    }


    public RyzeException(Throwable throwable, int code, String desc){
        super(desc,throwable);
        this.code = code;
        this.desc = desc;
    }

    public RyzeException(RyzeErrorCode errorCode){
        this(errorCode.getCode(), toMessage(errorCode));
    }

    public RyzeException(Throwable throwable, RyzeErrorCode errorCode){
        this(throwable, errorCode.getCode(), toMessage(errorCode));
    }

    public RyzeException(RyzeErrorCode errorCode, Object... args){
        this(errorCode.getCode(),toMessage(errorCode, args));
    }
    public RyzeException(Throwable throwable, RyzeErrorCode errorCode, Object... args){
        this(throwable, errorCode.getCode(),toMessage(errorCode, args));
    }

    /**
     * error code covert to message
     * @param errorCode
     * @param args
     * @return
     */
    private static String toMessage(RyzeErrorCode errorCode, Object... args){
        Assert.notNull(errorCode,"错误码不能为空");
        String desc = errorCode.getDesc();
        if(args!=null  && args.length>0){
            desc = MessageFormatter.arrayFormat(errorCode.getDesc(), args).getMessage();
        }
        String message = desc;
        return message;
    }

    public RyzeException withData(Object data){
        this.data = data;
        return this;
    }
}
